<template>
  <RadModal
    width="500px"
    :visible="visible"
    :loading="loading"
    title="授权用户数据"
    @visible-change="updateVisible"
    @ok="save"
  >
    <a-tree
      checkable
      check-strictly
      :tree-data="(tableData as any)"
      v-model:expanded-keys="expandedRowKeys"
      v-model:checkedKeys="checkedKeys"
    />
  </RadModal>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import RadModal from '@/components/RadModal/index.vue';
  import { User } from '@/api/system/user/model';
  import { grantUserOrg, userOwnOrgList } from '@/api/system/user';
  import { listOrganizations } from '@/api/system/organization';
  import { formatTreeData } from 'ele-admin-pro';
  import { Organization } from '@/api/system/organization/model';

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: User | null;
  }>();

  //默认展开数据
  const expandedRowKeys = ref<Array<number | string>>([]);
  //默认选中数据
  const checkedKeys = ref<Array<number | string> | undefined>([]);
  // 提交状态
  const loading = ref(false);
  const tableData = ref<Organization[]>([]);

  // 表格数据源
  const datasource = async () => {
    await listOrganizations().then((data) => {
      tableData.value = formatTreeData(data, (item) => {
        expandedRowKeys.value.push(item.id);
        if (item.children == null || item.children?.length == 0) {
          item.style = 'display:inline-flex';
        }
        return Object.assign({}, item, {
          title: item.name,
          key: item.id
        });
      });
      initCheckeys();
    });
  };
  const initCheckeys = async () => {
    checkedKeys.value = (await userOwnOrgList(props.data?.id))?.map(
      (element) => {
        return element.orgId;
      }
    );
  };
  const save = () => {
    loading.value = true;
    grantUserOrg({
      id: props.data?.id,
      orgId: props.data?.orgId,
      orgIdList: checkedKeys.value
    })
      .then((msg) => {
        loading.value = false;
        message.success(msg);
        updateVisible(false);
        emit('done');
      })
      .catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    async (visible) => {
      if (!visible) {
        checkedKeys.value = [];
      } else {
        await datasource();
      }
    }
  );
</script>

<style>
  .ant-tree-list-holder-inner {
    display: unset !important;
  }

  .ant-tree-node-content-wrapper .ant-tree-title {
    position: relative !important;
  }
</style>
